package com.usian.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dto.UserSearchDto;
import com.usian.model.search.pojos.ApUserSearch;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.mapper.ApUserSearchMapper;
import com.usian.search.service.ApUserSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Auther:ASS
 * @Date:2023/3/9 19:37
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService{


    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult findSearch(UserSearchDto dto) {

        if (dto==null || dto.getPageNum()<0 || dto.getPageSize()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //获取登录用户
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询用户行为实体 目的拿行为实体的
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());

        //判断参数
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //构建条件分页查询
        QueryWrapper<ApUserSearch> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ApUserSearch::getStatus,1).eq(ApUserSearch::getEntryId,apBehaviorEntry.getId());

        //分页
        Page page = new Page(dto.getPageNum(), dto.getPageSize());

        IPage result=this.page(page,queryWrapper);
        return ResponseResult.okResult(result.getRecords());
    }

    @Override
    public ResponseResult deleteSearch(UserSearchDto dto) {

        if (dto==null ||dto.getId()==null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        boolean b = this.update(Wrappers.<ApUserSearch>lambdaUpdate().set(ApUserSearch::getStatus, 0).eq(ApUserSearch::getId, dto.getId()));
        if (b){
           return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 插入搜索记录
     *
     * @param entryId
     * @param searchWords
     * @return
     */
    @Override
    @Async("taskExecutor")
    public void insert(Integer entryId, String searchWords) {
        System.out.println("====================================================================异步保存");

        if (entryId == null || StringUtils.isBlank(searchWords)){
            return;
        }

        //查询
        ApUserSearch apUserSearch = this.getOne(Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, entryId).
                                            eq(ApUserSearch::getKeyword, searchWords));

        if (apUserSearch!=null){
            if (apUserSearch.getStatus()==null){
                apUserSearch.setStatus(1);
                this.updateById(apUserSearch);
            }else if (apUserSearch.getStatus()==1){
                return;
            }
        }else {
            //3.如果不存在，保存新的数据
            apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(entryId);
            apUserSearch.setStatus(1);
            apUserSearch.setKeyword(searchWords);
            apUserSearch.setCreatedTime(new Date());
            save(apUserSearch);
        }
    }
}
